// vuex 状态管理

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
	// 数据源
	state: {
		userinfo: uni.getStorageSync('_userinfo') || {},
		historyList: uni.getStorageSync("_history") || []
	},
	// 改变数据源中的数据
	mutations: {
		SET_USERINFO(state, userinfo){
			state.userInfo = userinfo
		},
		SET_HISTORY_LIST(state, history) {
			state.historyList = history
		},
		CLEAR_HISTORY(state) {
			state.historyList = []
		}
	},
	// 页面调用action触发mutations去改变数据源
	actions: {
		set_userinfo({commit}, userinfo){
			uni.setStorageSync('_userinfo', userinfo)
			commit('SET_USERINFO', userinfo)
		},
		set_history_list({commit, state}, history) {
			let list = state.historyList
			list.unshift(history)
			uni.setStorageSync('_history', list)
			commit('SET_HISTORY_LIST', list)
		},
		clear_history({commit}) {
			uni.removeStorageSync('_history')
			commit('CLEAR_HISTORY')
		}
	}

})

export default store
